import { createRouter, createWebHashHistory } from 'vue-router'
import store from '../store'

import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
import LandscapeView from '../views/LandscapeView.vue'
import ShopCart from '../views/ShopCart.vue'
import OrderView from '../views/OrderView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import ItemDetail from '../views/ItemDetail.vue'
import UserInfo from '../views/UserInfo.vue'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      isLogin: false, //true表示需要登陆才能访问
    },
  },
  {
    path: '/userInfo',
    name: 'userInfo',
    component: UserInfo,
    meta: {
      isLogin: true,
    },
  },
  {
    path: '/itemDetail',
    name: 'itemDetail',
    component: ItemDetail,
    meta: {
      isLogin: true,
    },
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView,
    meta: {
      isLogin: false,
    },
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: {
      isLogin: false,
    },
  },
  {
    path: '/order',
    name: 'order',
    component: OrderView,
    meta: {
      isLogin: true,
    },
  },
  {
    path: '/shopCart',
    name: 'shopCart',
    component: ShopCart,
    meta: {
      isLogin: true,
    },
  },
  {
    path: '/landscape',
    name: 'landscape',
    component: LandscapeView,
    meta: {
      isLogin: false,
    },
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView,
    meta: {
      isLogin: false,
    },
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})
router.beforeEach((to, from, next) => {
  //store.state.isLogin的值是false，表示不需要登陆，否则需要登陆
  if (!to.meta.isLogin) {
    next()
  } else {
    if (store.state.isLogin) {
      next()
    } else {
      ElMessage({
        message: '请先登陆',
        type: 'success',
      })
    }
  }
})

export default router
